var SCOPES = 'https://www.googleapis.com/auth/drive';

/**
* Called when the client library is loaded to start the auth flow.
*/
function handleClientLoad() {
	window.setTimeout(checkAuth, 1);
}

/**
* Check if the current user has authorized the application.
*/
function checkAuth() {
	gapi.auth.authorize(
		{'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true},
		handleAuthResult);
}

/**
* Called when authorization server replies.
*
* @param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
	gapi.client.load('drive','v2',null);
	var authButton = document.getElementById('authorizeButton');
	var btn = document.getElementById('upload_file');
	btn.style.display = 'none';
	authButton.style.display = 'none';
	if (authResult && !authResult.error) {
		// Access token has been successfully retrieved, requests can be sent to the API.
		btn.style.display = 'block';
		btn.onclick = retrieveAllFiles;
	} else {
		// No access token could be retrieved, show the button to start the authorization flow.
		authButton.style.display = 'block';
		authButton.onclick = function() {
		gapi.auth.authorize(
			{'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false},
			handleAuthResult);
		};
	}
}

/**
* Start the file upload.
*
* @param {Object} evt Arguments from the file selector.
*/
function uploadFile(result) {
	var folderId = result[0]['id'];
	gapi.client.load('drive', 'v2', function() {
		var files = document.getElementsByClassName('yangdiupload');
		if(files.length>0){
			for(var i=0;i<files.length;i++){
				insertFile(files[i].files[0],folderId);
			}
		}
	});
}

/**
* Insert new file.
*
* @param {File} fileData File object to read data from.
* @param {Function} callback Function to call when the request is complete.
*/
function insertFile(fileData, folderId, callback) {
console.log(folderId+'h');
	const boundary = '-------314159265358979323846';
	const delimiter = "\r\n--" + boundary + "\r\n";
	const close_delim = "\r\n--" + boundary + "--";

	var reader = new FileReader();
	reader.readAsBinaryString(fileData);
	reader.onload = function(e) {
		var contentType = fileData.type || 'application/octet-stream';
		var metadata = {
			'title': fileData.name,
			'parents':[{'id':folderId,'kind':'drive#file'}],
			'mimeType': contentType
		};

		var base64Data = btoa(reader.result);
		var multipartRequestBody =
			delimiter +
			'Content-Type: application/json\r\n\r\n' +
			JSON.stringify(metadata) +
			delimiter +
			'Content-Type: ' + contentType + '\r\n' +
			'Content-Transfer-Encoding: base64\r\n' +
			'\r\n' +
			base64Data +
			close_delim;

		var request = gapi.client.request({
			'path': '/upload/drive/v2/files',
			'method': 'POST',
			'params': {'uploadType': 'multipart'},
			'headers': {
				'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
			},
			'body': multipartRequestBody});
		if (!callback) {
			callback = function(file) {
				console.log(file)
			};
		}
		request.execute(callback);
	}
}


/**
* Insert a file into a folder.
*
* @param {String} folderId ID of the folder to insert the file into.
* @param {String} fileId ID of the file to insert.
*/
function insertFileIntoFolder(folderId, fileId) {
	var body = {'id': folderId};
	var request = gapi.client.drive.parents.insert({
		'fileId': fileId,
		'resource': body
	});
	request.execute(function(resp) { });
}


/**
* Print a file's metadata.
*
* @param {String} fileId ID of the file to print metadata for.
*/
function printFile(fileId) {
	var request = gapi.client.drive.files.get({
		'fileId': fileId
	});
	request.execute(function(resp) {
		console.log('Title: ' + resp.title);
		console.log('Description: ' + resp.description);
		console.log('MIME type: ' + resp.mimeType);
	});
}

function folderExist(folderId){
	
	var btn = document.getElementById('upload_file');
	btn.onclick = uploadFile;
	
	//retrieveAllFiles({'q':'title = "<?php echo Yii::app()->params['gapi_folder_title'] ?>"'},returnFileList);
}

function buatFolderDrive(){
	gapi.client.load('drive','v2',null);
	var request = gapi.client.request({'path':'/drive/v2/files','method':'POST','body':{'title':'Hello World','mimeType':'application/vnd.google-apps.folder'}});
	request.execute(function(resp){
		uploadFile([resp]);
	});
}

/**
 * Retrieve a list of File resources.
 * @param q dictionary for search
 * @param {Function} folderNotExist is a callback Function to be call when not folder found.
 * @param {Function} folderExist is a callback Function to be called when folder found.
 */
function retrieveAllFiles(q,buatFolderDrives,folderExist) {
  var retrievePageOfFiles = function(request, result) {
    request.execute(function(resp) {
      result = result.concat(resp.items);
      var nextPageToken = resp.nextPageToken;
      if (nextPageToken) {
        request = gapi.client.drive.files.list({
          'pageToken': nextPageToken,
        });
        retrievePageOfFiles(request, result);
      } else {
        if(result == null || typeof result == 'undefined' || result.length<=0){
		 console.log('folder not exist, will create one');
		 console.log('folder created');
		 console.log('will upload file');
		 buatFolderDrive(); //setelah buat folder akan upload file
		 console.log('file uploaded');
		}else{
		 console.log('folder exist');
		 console.log('will upload file');
		 uploadFile(result);
		 console.log('file uploaded');
		}
      }
    });
  }
  var initialRequest = gapi.client.drive.files.list({'q':'title = "Hello World"'});
  return retrievePageOfFiles(initialRequest, []);
}